import React, { useState, useCallback } from "react";
import {
  Button,
  Table,
  Modal,
  message,
  Space,
  Form,
  Input,
  Popconfirm,
} from "antd";
import type { ColumnsType } from "antd/es/table";

// 内联定义 TableForm 组件，避免 React 19 严格模式下的导入问题
const TableForm = React.memo(
  ({
    onSubmit,
    initialValues,
  }: {
    onSubmit: (values: any) => void;
    initialValues?: any;
  }) => {
    // 使用 Form.useForm() 获取表单实例，用于程序化控制表单
    const [form] = Form.useForm();

    // useEffect: 当 initialValues 变化时，自动填充或重置表单
    React.useEffect(() => {
      if (initialValues) {
        form.setFieldsValue(initialValues);
      } else {
        form.resetFields();
      }
    }, [initialValues, form]);

    const handleSubmit = (values: any) => {
      onSubmit(values);
    };

    return (
      <Form
        form={form}
        name="tableForm"
        onFinish={handleSubmit}
        layout="vertical"
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          label="Name"
          name="name"
          rules={[{ required: true, message: "Please input your name!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Age"
          name="age"
          rules={[{ required: true, message: "Please input your age!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Address"
          name="address"
          rules={[{ required: true, message: "Please input your address!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Tags"
          name="tags"
          rules={[{ required: true, message: "Please input your tags!" }]}
        >
          <Input placeholder="输入标签，用逗号分隔" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            {initialValues ? "更新" : "提交"}
          </Button>
        </Form.Item>
      </Form>
    );
  }
);

TableForm.displayName = "TableForm";

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const TablePage: React.FC = () => {
  // useState: 管理表格数据状态
  const [data, setData] = useState<DataType[]>([
    {
      key: "1",
      name: "John Brown",
      age: 32,
      address: "New York No. 1 Lake Park",
      tags: ["nice", "developer"],
    },
    {
      key: "2",
      name: "Jim Green",
      age: 42,
      address: "London No. 1 Lake Park",
      tags: ["manager"],
    },
    {
      key: "3",
      name: "Joe Black",
      age: 32,
      address: "Sydney No. 1 Lake Park",
      tags: ["cool", "teacher"],
    },
    {
      key: "4",
      name: "Test User",
      age: 25,
      address: "Test Address",
      tags: [], // 空数组测试
    },
    {
      key: "5",
      name: "Another User",
      age: 30,
      address: "Another Address",
      tags: ["loser"], // 特殊标签测试
    },
    {
      key: "6",
      name: "Alice Johnson",
      age: 28,
      address: "San Francisco Bay Area",
      tags: ["developer", "frontend"],
    },
    {
      key: "7",
      name: "Bob Wilson",
      age: 35,
      address: "Seattle Downtown",
      tags: ["manager", "senior"],
    },
    {
      key: "8",
      name: "Carol Davis",
      age: 29,
      address: "Austin Tech Hub",
      tags: ["designer", "creative"],
    },
    {
      key: "9",
      name: "David Miller",
      age: 33,
      address: "Boston Innovation District",
      tags: ["engineer", "backend"],
    },
    {
      key: "10",
      name: "Eva Garcia",
      age: 27,
      address: "Miami Beach",
      tags: ["marketing", "social"],
    },
  ]);

  // useState: 管理模态框和编辑状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [editingRecord, setEditingRecord] = useState<DataType | null>(null);
  const [loading, setLoading] = useState(false); // 添加加载状态

  // 定义表格列配置
  const columns: ColumnsType<DataType> = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "Tags",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => {
        // 安全检查：确保 tags 是数组且不为空
        if (!tags || !Array.isArray(tags) || tags.length === 0) {
          return <span style={{ color: "#999" }}>无标签</span>;
        }

        return (
          <>
            {tags.map((tag, index) => {
              // 安全检查：确保 tag 是字符串
              if (typeof tag !== "string") {
                return null;
              }

              // 改进的颜色逻辑 - 使用更好的对比度组合
              let backgroundColor = "#1890ff"; // 默认蓝色背景
              let textColor = "#ffffff"; // 默认白色文字

              if (tag.length > 5) {
                backgroundColor = "#722ed1"; // 紫色
              }
              if (tag.toLowerCase() === "loser") {
                backgroundColor = "#f5222d"; // 红色
              }
              if (tag.toLowerCase() === "developer") {
                backgroundColor = "#1890ff"; // 蓝色
              }
              if (tag.toLowerCase() === "manager") {
                backgroundColor = "#722ed1"; // 紫色
              }
              if (tag.toLowerCase() === "teacher") {
                backgroundColor = "#fa8c16"; // 橙色
              }
              if (tag.toLowerCase() === "nice") {
                backgroundColor = "#52c41a"; // 绿色
              }
              if (tag.toLowerCase() === "cool") {
                backgroundColor = "#13c2c2"; // 青色
              }

              return (
                <span
                  key={`${tag}-${index}`} // 使用更安全的 key
                  style={{
                    color: textColor,
                    backgroundColor: backgroundColor,
                    padding: "2px 8px",
                    borderRadius: "4px",
                    marginRight: "4px",
                    fontSize: "12px",
                    display: "inline-block",
                    marginBottom: "2px",
                    fontWeight: "500", // 添加字体粗细提高可读性
                    textShadow: "0 1px 2px rgba(0,0,0,0.2)", // 添加文字阴影
                    border: "1px solid rgba(0,0,0,0.1)", // 添加边框
                  }}
                >
                  {tag}
                </span>
              );
            })}
          </>
        );
      },
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => handleEdit(record)}
            style={{ padding: 0 }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除确认"
            description="确定要删除这条记录吗？"
            onConfirm={() => handleDelete(record.key)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger style={{ padding: 0 }}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 打开新增模态框
  const showModal = () => {
    setIsEditMode(false);
    setEditingRecord(null);
    setIsModalVisible(true);
  };

  // 关闭模态框并重置状态
  const handleCancel = () => {
    setIsModalVisible(false);
    setIsEditMode(false);
    setEditingRecord(null);
  };

  // 打开编辑模态框
  const handleEdit = (record: DataType) => {
    setIsEditMode(true);
    setEditingRecord(record);
    setIsModalVisible(true);
  };

  // 删除记录
  const handleDelete = (key: string) => {
    setData((prevData) => prevData.filter((item) => item.key !== key));
    message.success("删除成功！");
  };

  // useCallback: 缓存表单提交函数，避免不必要的重新渲染
  const handleFormSubmit = useCallback(
    (values: any) => {
      // 处理标签：将逗号分隔的字符串转换为数组，添加安全检查
      let tags: string[] = [];
      if (values.tags && typeof values.tags === "string") {
        tags = values.tags
          .split(",")
          .map((tag: string) => tag.trim())
          .filter((tag: string) => tag.length > 0); // 过滤空标签
      }

      if (isEditMode && editingRecord) {
        // 编辑模式：更新现有记录
        const updatedData: DataType = {
          ...editingRecord,
          name: values.name,
          age: parseInt(values.age),
          address: values.address,
          tags: tags,
        };

        setData((prevData) =>
          prevData.map((item) =>
            item.key === editingRecord.key ? updatedData : item
          )
        );
        message.success("更新成功！");
      } else {
        // 新增模式：添加新记录
        const newData: DataType = {
          key: Date.now().toString(),
          name: values.name,
          age: parseInt(values.age),
          address: values.address,
          tags: tags,
        };

        setData((prevData) => [...prevData, newData]);
        message.success("添加成功！");
      }

      // 重置模态框状态
      setIsModalVisible(false);
      setIsEditMode(false);
      setEditingRecord(null);
    },
    [isEditMode, editingRecord]
  );

  // 分页事件处理函数
  const handleTableChange = async (
    pagination: any,
    filters: any,
    sorter: any
  ) => {
    console.log("=== 分页事件触发 ===");
    console.log("当前页码:", pagination.current);
    console.log("每页条数:", pagination.pageSize);
    console.log("总数据条数:", pagination.total);
    console.log(
      "当前页数据范围:",
      `${(pagination.current - 1) * pagination.pageSize + 1}-${Math.min(
        pagination.current * pagination.pageSize,
        pagination.total
      )}`
    );

    // 模拟网络请求参数
    const requestParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      filters: filters,
      sorter: sorter,
    };

    console.log("模拟网络请求参数:", requestParams);

    // 设置加载状态
    setLoading(true);

    try {
      // 模拟网络请求延迟
      console.log("开始模拟网络请求...");
      await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟500ms延迟

      console.log("网络请求成功!");
      console.log(
        "获取到的数据范围:",
        `${(pagination.current - 1) * pagination.pageSize + 1}-${Math.min(
          pagination.current * pagination.pageSize,
          pagination.total
        )}`
      );

      // 这里可以添加实际的数据更新逻辑
      // const response = await fetch('/api/data', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(requestParams)
      // });
      // const newData = await response.json();
      // setData(newData);
    } catch (error) {
      console.error("网络请求失败:", error);
      message.error("数据加载失败，请重试");
    } finally {
      setLoading(false);
      console.log("=== 分页事件结束 ===\n");
    }
  };

  return (
    <div style={{ padding: "24px" }}>
      <div style={{ marginBottom: "16px" }}>
        <Button type="primary" onClick={showModal}>
          添加数据
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        loading={loading} // 添加加载状态
        pagination={{
          showSizeChanger: true, // 显示每页条数选择器
          showQuickJumper: true, // 显示快速跳转
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条`, // 显示总数
          pageSizeOptions: ["5", "10", "20", "50"], // 每页条数选项
          defaultPageSize: 5, // 默认每页5条
        }}
        onChange={handleTableChange} // 添加分页事件处理
      />

      <Modal
        title={isEditMode ? "编辑数据" : "添加新数据"}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={600}
      >
        <TableForm
          onSubmit={handleFormSubmit}
          initialValues={
            isEditMode && editingRecord
              ? {
                  name: editingRecord.name,
                  age: editingRecord.age.toString(),
                  address: editingRecord.address,
                  tags:
                    editingRecord.tags && editingRecord.tags.length > 0
                      ? editingRecord.tags.join(", ")
                      : "",
                }
              : undefined
          }
        />
      </Modal>
    </div>
  );
};

export default TablePage;
